﻿#include "PortNum.h"
#include "C0C_Def.h"
#include "Utils.h"

#include <QDebug>
#include <windows.h>

namespace PortNum {

int GetPortNum(
    HDEVINFO hDevInfo,
    PSP_DEVINFO_DATA pDevInfoData)
{
    HKEY hKey;

    hKey = SetupDiOpenDevRegKey(hDevInfo, pDevInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);

    if (hKey == INVALID_HANDLE_VALUE) {
        qDebug() << "GetPortNum: SetupDiOpenDevRegKey() failed:" << Utils::formatWinError(GetLastError());
        return -1;
    }

    int num;
    DWORD len;
    DWORD portNum;

    len = sizeof(portNum);

    LONG rc = RegQueryValueEx(hKey, C0C_REGSTR_VAL_PORT_NUM, NULL, NULL, (PBYTE)&portNum, &len);
    if (rc == ERROR_SUCCESS) {
        num = portNum;
    } else {
        qDebug() << "GetPortNum: RegQueryValueEx('" C0C_REGSTR_VAL_PORT_NUM "') failed:" << Utils::formatWinError(rc);
        num = -1;
    }

    RegCloseKey(hKey);

    return num;
}

LONG SetPortNum(
    HDEVINFO hDevInfo,
    PSP_DEVINFO_DATA pDevInfoData,
    int num)
{
    HKEY hKey;

    hKey = SetupDiCreateDevRegKey(hDevInfo, pDevInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, NULL, NULL);

    if (hKey == INVALID_HANDLE_VALUE) {
        qDebug() << "SetPortNum: SetupDiCreateDevRegKey() failed:" << Utils::formatWinError(GetLastError());
        return GetLastError();
    }

    DWORD portNum = num;

    LONG err = RegSetValueEx(hKey, C0C_REGSTR_VAL_PORT_NUM, NULL, REG_DWORD, (PBYTE)&portNum, sizeof(portNum));

    if (err != ERROR_SUCCESS) {
        qDebug() << "SetPortNum: RegSetValueEx('" C0C_REGSTR_VAL_PORT_NUM "'," << num << ") failed:" << Utils::formatWinError(err);
    }

    RegCloseKey(hKey);

    return err;
}

}
